package cn.edu.sdjzu.xg.eagle.Service;

import cn.edu.sdjzu.xg.eagle.dao.DepartmentImpl;
import cn.edu.sdjzu.xg.eagle.dao.SchoolDaoImpl;
import cn.edu.sdjzu.xg.eagle.entity.Pagination;
import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.exception.BysjException;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;


public class SchoolService implements SchoolServiceInterface {
    private static SchoolServiceInterface schoolServiceInterface = null;

    public SchoolService() {}

    public static SchoolServiceInterface getInstance() {
        if (schoolServiceInterface == null) {
            schoolServiceInterface = new SchoolService();
        }
        return schoolServiceInterface;
    }
    @Override
    public Collection<School> findAll() throws SQLException, BysjException {
        return SchoolDaoImpl.getInstance().findAll();
    }

    @Override
    public Collection<School> findAll(Pagination pagination) throws SQLException, BysjException {
        return SchoolDaoImpl.getInstance().findAll(pagination);
    }

    @Override
    public School find(Long id) throws SQLException, BysjException {
        return SchoolDaoImpl.getInstance().find(id);
    }

    @Override
    public boolean delete(Long id) throws SQLException, BysjException {
        School school = SchoolDaoImpl.getInstance().find(id);
        int countDepartsOfSchool = DepartmentImpl.getInstance().countAll(school);
        if (countDepartsOfSchool == 0) {
            return SchoolDaoImpl.getInstance().delete(id);
        }else{
            throw new BysjException(school.getDescription()+"仍然有下属系，不能删除");
        }
    }
    @Override
    public boolean add(School school)throws SQLException{
        Connection connection = JdbcHelper.getConn();
        boolean added = SchoolDaoImpl.getInstance().add(connection, school);
        JdbcHelper.close(connection);
        return added;
    }

    public static void main(String[] args) throws SQLException, BysjException {
        Long id = 11L;
        System.out.println(SchoolDaoImpl.getInstance().find(id));
        SchoolService.getInstance().delete(id);
        System.out.println(SchoolDaoImpl.getInstance().find(id));
    }

}
